package org.dongchao.statistics.config;

import org.apache.commons.lang3.StringUtils;
import org.dongchao.statistics.exe.RequestResultHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * spring resttemplate config , our used deafult build.
 * @author dongyazhuo
 */
@Configuration
public class ApplicationConfig implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Value("${config.handller.impl}")
	String hanndlerImpl;

	@Autowired
	RestTemplateBuilder restTemplateBuilder;

	@Bean
	public RestTemplate restTemplate() {
		return restTemplateBuilder.build();
	}

	@Bean("requestResultHandller")
	public RequestResultHandler requestResultHandller() throws Exception {
		if (StringUtils.isBlank(hanndlerImpl)) {
			return applicationContext.getBean("printRequestResultHandler", RequestResultHandler.class);
		} else {
			return applicationContext.getBean(hanndlerImpl, RequestResultHandler.class);
		}
	}

}
